package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.utils.StringUtils;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.utils.StringTool;
import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.api.vo.request.ScreensaverReqVo;
import com.iot08.api.vo.request.WallpaperSettingReqVo;
import com.iot08.common.constant.Const;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.Screensaver;
import com.iot08.common.service.base.BaseAdminService;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * @author cwj
 * @description
 * @date 2024/12/18 11:54
 **/
@Slf4j
@Service
public class ScreensaverService extends BaseService<Screensaver> {
    @Resource
    private KafkaService kafkaService;

    @Resource
    private RedisClusterService redisClusterService;

    @Resource
    private BaseBucketTool baseBucketTool;

    @Value("${aliyun.oss.domainurl}")
    private String ossDomainUrl;


    /**
     * @description 查询专属屏保
     * @author cwj
     * @param [imei]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2024/12/18 15:16
     **/
    public ResponseMap queryScreensaver(String imei){
        Screensaver screensaver =  queryScreensaverByImei(imei);
        ResponseMap res = ResponseMap.success();
        if(ObjectUtils.isEmpty(screensaver)){
            return res;
        }
        if(StringUtils.isEmpty(screensaver.getImageUrl())){
            res.put("imageUrl","");
        } else {
            res.put("imageUrl",baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH +screensaver.getImageUrl());
        }
        return res;
    }

    /**
     * @description 设置专属屏保
     * @author cwj
     * @param [imei, vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2024/12/18 15:16
     **/
    public ResponseMap settingScreensaver(String imei, ScreensaverReqVo vo, MultipartFile image){
        //检查设备是否在线，不在线不能下发
        String onlineStatus = redisClusterService.hget(imei, ConstCacheField.ONLINE_STATUS);
        if (!"1".equals(onlineStatus)) {
            return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
        }
        try {
            //保存数据，上传文件，删除旧文件
            saveOrUpdateScreensaver(imei, vo,image);
        } catch (IOException e) {
            log.error("更新数据或上传文件时发生异常，异常信息为：{}",e.getMessage());
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.result.fileUpload.exception");
        }
        //发送设置专属屏保的指令
        JSONObject kafkaJson = new JSONObject();
        kafkaJson.put("imageUrl", vo.getImageUrl());
        kafkaService.emitDeviceDemand(imei, ConstKafka.DEV_SCREENSAVER, kafkaJson,vo.getOpenid());
        return ResponseMap.success();
    }

    /**
     * @description 保存或更新专属屏保
     * @author cwj
     * @param [imei, vo]
     * @return void
     * @date @time 2024/12/18 15:39
     **/
    private void saveOrUpdateScreensaver(String imei, ScreensaverReqVo vo,MultipartFile image) throws IOException {
        //查询已经设置的壁纸
        Screensaver screensaver = queryScreensaverByImei(imei);
        if(!ObjectUtils.isEmpty(image)){
            //上传当前的屏保文件
            String fileName = BaseBucketTool.createFileNameToJpg();
            //上传图片
            baseBucketTool.upload(BaseBucketTool.DEVICE_COMMON_PATH + fileName, image, 1);
            vo.setImageUrl(baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH + fileName);
            //保存或更新指令
            if(ObjectUtils.isEmpty(screensaver)){
                screensaver = new Screensaver();
                screensaver.setImei(imei);
                screensaver.setImageUrl(fileName);
                screensaver.setCreateTime(new Date());
                screensaver.setUpdateTime(new Date());
                this.save(screensaver);
            } else {
                //删除旧的屏保图片，并更新用户设置的屏保信息
                deleteOldImage(fileName, screensaver);
            }
        } else {
            if(!StringUtils.isEmpty(vo.getImageUrl())){
                vo.setImageUrl("");
            }
            //使用默认图片，之前存在图片需要删除
            if(!ObjectUtils.isEmpty(screensaver)){
                //获取旧的屏保图片名
                deleteOldImage("", screensaver);
            }
        }
    }
    
    /**
     * @description 保存或更新设备设置的壁纸信息
     * @author cwj
     * @param [imei, vo]
     * @return void
     * @date @time 2025/3/13 9:33
     **/
    public void saveOrUpdateWpScreensaver(WallpaperSettingReqVo vo){
        Screensaver screensaver = queryScreensaverByImei(vo.getImei());
        String fileName = vo.getImageUrl();
        //StringTool.obtainFileNameByUrl(vo.getImageUrl());
        if(ObjectUtils.isEmpty(screensaver)){
            screensaver = new Screensaver();
            screensaver.setImei(vo.getImei());
            screensaver.setImageUrl(fileName);
            screensaver.setWid(vo.getWid());
            screensaver.setCreateTime(new Date());
            screensaver.setUpdateTime(new Date());
            this.save(screensaver);
        } else {
            //更新用户设置的屏保信息
            Update update = new Update();
            update.set("imageUrl", fileName);
            update.set("wid",vo.getWid());
            update.set("updateTime",new Date());
            this.updateById(new ObjectId(screensaver.getId()),update);
        }
    }

    /**
     * @description 删除旧的图片并更新用户设置的壁纸信息
     * @author cwj
     * @param [vo, screensaver]
     * @return void
     * @date @time 2025/2/7 17:11
     **/
    private void deleteOldImage(String fileName, Screensaver screensaver) {
        String oldFileName = screensaver.getImageUrl();
        Update ssUpdate = new Update();
        ssUpdate.set("imageUrl", fileName);
        ssUpdate.set("updateTime",new Date());
        this.updateById(new ObjectId(screensaver.getId()),ssUpdate);
        if (StringUtil.isNotBlank(oldFileName) && StringUtils.isEmpty(screensaver.getWid())) {
            //删除旧文件
            baseBucketTool.delFile(BaseBucketTool.DEVICE_COMMON_PATH + oldFileName);
        }
    }

    /**
     * @description 根据imei查询专属屏保
     * @author cwj
     * @param [imei]
     * @return com.iot08.common.entity.app.Screensaver
     * @date @time 2024/12/18 15:46
     **/
    public Screensaver queryScreensaverByImei(String imei) {
        Query query = new Query(Criteria.where("imei").is(imei));
        query.with(Sort.by(Sort.Order.desc("createTime"))).limit(1);
        Screensaver screensaver = this.findOne(query);
        return screensaver;
    }
}
